<script setup>
import { onMounted, reactive, ref } from 'vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  callback: {
    type: Object,
    attributes: {}
  }
})

const formRef = ref()

const form = reactive({})

const rules = reactive({
  name: [{ required: true, message: '名称不能为空!', trigger: 'blur' }]
})

const initForm = () => {
  if (props.data) {
    Object.keys(props.data).forEach((key) => {
      form[key] = props.data[key]
    })
  }
}

const formatForm = () => {
  const result = {}
  Object.keys(form).forEach((key) => {
    result[key] = form[key]
  })
  return result
}

const submitForm = () => {
  return new Promise((resolve) => {
    formRef.value.validate((valid) => {
      let res = null
      if (valid) {
        res = formatForm()
      }
      resolve(res)
    })
  })
}

defineExpose({
  submitForm
})

onMounted(() => {
  initForm()
})
</script>

<template>
  <div class="form-wrapper">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="70px">
      <el-form-item label="名称：" prop="name">
        <el-input v-model="form.name" type="text" placeholder="请输入内容"> </el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.form-wrapper {
  width: 500px;
}
</style>
